package com.xiyu.service.repository.material.order;

import com.xiyu.service.model.material.info.MaterialCategoryFetcher;
import com.xiyu.service.model.material.info.MaterialInfoFetcher;
import com.xiyu.service.model.material.order.*;
import com.xiyu.service.model.material.stock.MaterialStockDetailFetcher;
import com.xiyu.service.vo.material.transfer.TransferPageQueryInput;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.springframework.util.StringUtils;
import java.util.Optional;

public interface MaterialTransferRepository extends JRepository<MaterialTransfer, Long> {
    MaterialTransferTable materialTransferTable = MaterialTransferTable.$;

    default Page<MaterialTransfer> pageQuery(TransferPageQueryInput inputVO){
        return sql().createQuery(materialTransferTable)
                .whereIf(StringUtils.hasText(inputVO.getTransferNo()),
                        () -> materialTransferTable.transferNo().like(inputVO.getTransferNo()))
                .whereIf(inputVO.getInWarehouseId() != null,
                        materialTransferTable.inWarehouseId().eq(inputVO.getInWarehouseId()))
                .whereIf(inputVO.getOutWarehouseId() != null,
                        materialTransferTable.outWarehouseId().eq(inputVO.getOutWarehouseId()))
                .whereIf(inputVO.getStatus() != null,
                        () -> materialTransferTable.status().in(inputVO.getStatus()))
                .orderBy(materialTransferTable.id().desc())
                .select(materialTransferTable)
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

    default Optional<MaterialTransfer> findDetailById(Long id){
        return sql().createQuery(materialTransferTable)
                .where(materialTransferTable.id().eq(id))
                .select(materialTransferTable.fetch(
                        MaterialTransferFetcher.$.allTableFields().details(
                            MaterialTransferDetailFetcher.$.allTableFields().material(
                                MaterialInfoFetcher.$.allTableFields().category(
                                        MaterialCategoryFetcher.$.allTableFields()
                                )
                            ).stockDetail(MaterialStockDetailFetcher.$.allTableFields())
                        )
                    )
                ).fetchOptional();
    }

    default void updateStatus(Long id, Integer status){
        sql().createUpdate(materialTransferTable)
                .set(materialTransferTable.status(), status)
                .where(materialTransferTable.id().eq(id))
                .execute();
    }

}